import {ModalForm, ProFormCheckbox, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import {Button, Card, Col, Form, message, Modal, Row, Space, Typography} from 'antd';
import {EditOutlined} from '@ant-design/icons';
import React, {useEffect, useState} from 'react';
import {
  allPermissions,
  insertRole,
  insertPermission,
  updatePermission,
  updateRole
} from '@/services/rolesPermission/api';

const {Title, Text} = Typography;

export type FormValueType = Partial<API.RolesListItem>;

export type UpdateFormProps = {
  onCancel: () => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  modalOpen: boolean;
  values: FormValueType;
};

const CreateUpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [form] = Form.useForm();
  const [permissionForm] = Form.useForm();
  const [permissions, setPermissions] = useState<API.RolesListPermissionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [addPermissionModalOpen, setAddPermissionModalOpen] = useState(false);
  const [addingPermission, setAddingPermission] = useState(false);
  const [editPermissionModalOpen, setEditPermissionModalOpen] = useState(false);
  const [editingPermission, setEditingPermission] = useState<API.RolesListPermissionItem | null>(null);
  const [updatingPermission, setUpdatingPermission] = useState(false);

  const fetchPermissions = async () => {
    try {
      setLoading(true);
      const result = await allPermissions();
      setPermissions(result.data || []);
    } catch (error: any) {
      console.error('获取权限列表失败:', error);
      message.error('获取权限列表失败，请重试');
      setPermissions([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (props.modalOpen) {
      fetchPermissions();
    }
  }, [props.modalOpen]);

  useEffect(() => {
    if (permissions.length > 0) {
      const permissionIds = props.values.permissions?.map(p => p.id) || [];
      form.setFieldsValue({...props.values, permissionIds});
    }
  }, [permissions, props.values, form]);

  useEffect(() => {
    if (!props.modalOpen) {
      form.resetFields();
    }
  }, [props.modalOpen, form]);

  const handleFinish = async (formValues: FormValueType) => {
    const params = {id: props.values.id, ...formValues};
    try {
      if (params.id == 0){
        await insertRole(params);
      }else{
        await updateRole(params);
      }
      message.success('操作成功');
      props.onSubmit(params);
    } catch (error) {
      message.error('操作失败，请重试');
    }
  };

  const handleAddNewPermission = () => {
    setAddPermissionModalOpen(true);
  };

  const handleAddPermissionSubmit = async (values: API.UpsertPermission) => {
    try {
      setAddingPermission(true);
      await insertPermission(values);
      message.success('权限添加成功');
      setAddPermissionModalOpen(false);
      permissionForm.resetFields();
      // 刷新权限列表
      await fetchPermissions();
    } catch (error: any) {
      console.error('添加权限失败:', error);
      message.error('添加权限失败，请重试');
    } finally {
      setAddingPermission(false);
    }
  };

  const handleEditPermission = (permission: API.RolesListPermissionItem) => {
    setEditingPermission(permission);
    setEditPermissionModalOpen(true);
    permissionForm.setFieldsValue({
      name: permission.name,
      description: permission.description,
    });
  };

  const handleUpdatePermissionSubmit = async (values: API.UpsertPermission) => {
    if (!editingPermission) return;

    try {
      setUpdatingPermission(true);
      await updatePermission({ ...values, id: editingPermission.id });
      message.success('权限更新成功');
      setEditPermissionModalOpen(false);
      setEditingPermission(null);
      permissionForm.resetFields();
      // 刷新权限列表
      await fetchPermissions();
    } catch (error: any) {
      console.error('更新权限失败:', error);
      message.error('更新权限失败，请重试');
    } finally {
      setUpdatingPermission(false);
    }
  };

  return (
    <ModalForm
      title={props.values.id ? '编辑角色' : '新建角色'}
      width="640px"
      form={form}
      open={props.modalOpen}
      onFinish={handleFinish}
      onOpenChange={(visible) => {
        if (!visible) {
          props.onCancel();
        }
      }}
    >
      <Row gutter={24}>
        <Col span={10}>
          <Card
            title={<Title level={5} style={{margin: 0}}>角色信息</Title>}
            size="small"
            style={{height: '100%'}}
          >
            <Space direction="vertical" style={{width: '100%'}} size="large">
              <ProFormText
                name="name"
                label="角色名称"
                rules={[{required: true, message: '请输入角色名称'}]}
              />
              <ProFormTextArea
                name="description"
                label="角色描述"
                placeholder="请输入角色描述"
                rows={4}
              />
            </Space>
          </Card>
        </Col>

        <Col span={14}>
          <Card
            title={
              <Space>
                <Title level={5} style={{margin: 0}}>权限分配</Title>
                <Text type="secondary">({permissions.length} 个权限可选)</Text>
              </Space>
            }
            size="small"
            style={{height: '100%'}}
            extra={
              <Button type="link" onClick={handleAddNewPermission} size="small">
                + 新增权限
              </Button>
            }
          >
            {loading ? (
              <div style={{textAlign: 'center', padding: '40px 0', color: '#999'}}>
                加载权限中...
              </div>
            ) : (
              <div style={{maxHeight: '300px', overflowY: 'auto'}}>
                <style>
                  {`
                    .permission-item:hover .permission-actions {
                      opacity: 1 !important;
                    }
                  `}
                </style>
                <ProFormCheckbox.Group
                  name="permissionIds"
                  options={permissions.map((p: API.RolesListPermissionItem) => ({
                    label: (
                      <div className="permission-item" style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%'}}>
                        <Space direction="vertical" size={0}>
                          <Text style={{color: '#595959', fontWeight: 500}}>{p.name}</Text>
                          {p.description && <Text type="secondary" style={{fontSize: '12px'}}>{p.description}</Text>}
                        </Space>
                        {p.namespaceId != 0 && <Space size="small" style={{opacity: 0.3}} className="permission-actions">
                          <Button
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleEditPermission(p);
                            }}
                            style={{color: '#1890ff'}}
                          />
                        </Space>}
                      </div>
                    ),
                    value: p.id
                  }))}
                />
              </div>
            )}
          </Card>
        </Col>
      </Row>

      <Modal
        title="新增权限"
        open={addPermissionModalOpen}
        onCancel={() => {
          setAddPermissionModalOpen(false);
          permissionForm.resetFields();
        }}
        footer={[
          <Button key="cancel" onClick={() => {
            setAddPermissionModalOpen(false);
            permissionForm.resetFields();
          }}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={addingPermission}
            onClick={() => {
              permissionForm.validateFields().then(handleAddPermissionSubmit);
            }}
          >
            确定
          </Button>
        ]}
      >
        <Form
          form={permissionForm}
          layout="vertical"
          style={{marginTop: '20px'}}
        >
          <Form.Item
            name="name"
            label="权限名称"
            rules={[{required: true, message: '请输入权限名称'}]}
          >
            <input
              placeholder="请输入权限名称，比如：users:read"
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '6px',
                fontSize: '14px'
              }}
            />
          </Form.Item>
          <Form.Item
            name="description"
            label="权限描述"
            rules={[{required: true, message: '请输入权限描述'}]}
          >
            <textarea
              placeholder="请输入权限描述，比如：用户查看权限"
              rows={3}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '6px',
                fontSize: '14px',
                resize: 'vertical'
              }}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑权限弹框 */}
      <Modal
        title="编辑权限"
        open={editPermissionModalOpen}
        onCancel={() => {
          setEditPermissionModalOpen(false);
          setEditingPermission(null);
          permissionForm.resetFields();
        }}
        footer={[
          <Button key="cancel" onClick={() => {
            setEditPermissionModalOpen(false);
            setEditingPermission(null);
            permissionForm.resetFields();
          }}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={updatingPermission}
            onClick={() => {
              permissionForm.validateFields().then(handleUpdatePermissionSubmit);
            }}
          >
            确定
          </Button>
        ]}
      >
        <Form
          form={permissionForm}
          layout="vertical"
          style={{marginTop: '20px'}}
        >
          <Form.Item
            name="name"
            label="权限名称"
            rules={[{required: true, message: '请输入权限名称'}]}
          >
            <input
              placeholder="请输入权限名称，比如：users:read"
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '6px',
                fontSize: '14px'
              }}
            />
          </Form.Item>
          <Form.Item
            name="description"
            label="权限描述"
            rules={[{required: true, message: '请输入权限描述'}]}
          >
            <textarea
              placeholder="请输入权限描述，比如：用户查看权限"
              rows={3}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '6px',
                fontSize: '14px',
                resize: 'vertical'
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </ModalForm>
  );
};

export default CreateUpdateForm;
